package com.zxlspace.collection;

public class SxtLinkedList {

    private Node first;  //第一个节点

    private Node last; //最后一个节点

    private int size;

    public SxtLinkedList() {

    }

    public int size() {
        return size;
    }

    public void add(Object obj) {
        Node n = new Node();

        if (null == first) {
            n.setPrev(null);
            n.setObj(obj);
            n.setNext(null);

            first = n;
            last = n;
        }else {
            n.setPrev(last);
            n.setObj(obj);
            n.setNext(null);

            last.setNext(n);
            last = n;
        }
        size++;
    }

    private void rangeCheck(int index) {
        if (index < 0 || index >= size) {
            throw new IllegalArgumentException();
        }
    }

    public Object get(int index) {
        rangeCheck(index);
        Node temp = node(index);
        if (temp != null) {
            return temp.obj;
        }
        return null;
    }

    //根据索引查找节点
    public Node node(int index) {
        Node temp = null;

        if (null != first) {
            //正序查找；size>>1 相当于 siz/2，但是效率要比/2高, size<<1 相当于size*2
            if (index < (size >> 1)) {
                temp = first;
                for (int i=0; i<index; i++) {
                    temp = temp.next;
                }
            }else { //反序查找
                temp = last;
                for (int i=size-1;i>index;i--) {
                    temp = temp.prev;
                }
            }
        }
        return temp;
    }

    public void remove(int index) {
        rangeCheck(index);
        Node temp = node(index);

        if (temp != null) {
            Node up = temp.prev;
            Node down = temp.next;
            up.next = down;
            down.prev = up;
            size--;
        }
    }

    public void add(int index, Object obj) {
        Node temp = node(index);

        Node newNode = new Node();
        newNode.obj = obj;
        if (temp !=null) {
            Node up = temp.prev;
            up.next = newNode;
            newNode.prev = up;
            newNode.next = temp;
            temp.prev = newNode;
            size++;
        }
    }


    public static void main(String[] args) {
        SxtLinkedList linkedList = new SxtLinkedList();
        linkedList.add("aaa");
        linkedList.add("aaa");
        linkedList.add("aaa");
        linkedList.add("bbb");
        linkedList.add("ccc");
        linkedList.add("fff");

//        linkedList.remove(2);

        System.out.println(linkedList.size());
        System.out.println(linkedList.get(1));

    }
}
